import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import path, { resolve } from 'path';

export default ({ mode }) => {
  return defineConfig({
    plugins: [vue(), vueJsx()],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '@components': path.resolve(__dirname, 'src/components'),
        '@utils': path.resolve(__dirname, 'src/utils'),
        '@api': path.resolve(__dirname, 'src/api'),
        '@views': path.resolve(__dirname, 'src/views'),
        '@stores': path.resolve(__dirname, 'src/stores'),
        '@assets': path.resolve(__dirname, 'src/assets'),
        '@style': path.resolve(__dirname, 'src/style')
      },
    },
    base: loadEnv(mode, process.cwd()).VITE_BASE_URL,
    server: {
      host: '0.0.0.0',
      port: parseInt(loadEnv(mode, process.cwd()).VITE_PORT),
      open: true,
      proxy: {
        '/dev-api': {
          target: 'http://localhost:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/dev-api/, ''),
          timeout: 30000,
          ws: true,
          retry: 0,
          configure: (proxy, options) => {
            proxy.on('error', (err) => {
              console.log('代理错误', err);
            });
            proxy.on('proxyReq', (proxyReq, req) => {
              // console.log('正在请求：', req.url);
              // 修改请求头，禁用缓存
              proxyReq.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
              proxyReq.setHeader('Pragma', 'no-cache');
              proxyReq.setHeader('Expires', '0');
            });
            proxy.on('proxyRes', (proxyRes, req, res) => {
              // 修改响应头，禁用缓存
              proxyRes.headers['cache-control'] = 'no-cache, no-store, must-revalidate';
              proxyRes.headers['pragma'] = 'no-cache';
              proxyRes.headers['expires'] = '0';
            });
          }
        },
      },
    },
    build: {
      target: 'es2015',
      outDir: 'dist',
      emptyOutDir: true,
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: '[ext]/[name]-[hash].[ext]'
        }
      }
    },
  });
};
